package com.gitee.absolute_spirit.hiot_android

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.gitee.absolute_spirit.hiot_android.mqtt.MqttService
import com.gitee.absolute_spirit.hiot_android.ui.home.HomeView
import com.gitee.absolute_spirit.hiot_android.ui.ir.InfraredRemoteController
import com.gitee.absolute_spirit.hiot_android.ui.light.SwitchView
import com.gitee.absolute_spirit.hiot_android.ui.theme.AppTheme
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private lateinit var mqttService: MqttService
    private var mBound: Boolean = false

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MqttService.MqttBinder
            mqttService = binder.getService()
            mBound = true
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            mBound = false
        }

    }

    override fun onStop() {
        super.onStop()
        unbindService(connection)
        mBound = false
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Intent(this, MqttService::class.java).also { intent ->
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
        val filter = IntentFilter(ACTION_MQTT_ACTION)
        if (Build.VERSION.SDK_INT >= 33) {
            applicationContext.registerReceiver(object : BroadcastReceiver(){
                override fun onReceive(context: Context?, intent: Intent?) {
                    val message: String? = intent?.extras?.getString("")
                    Log.i("TEST", "收到消息： $message")
                }
            }, filter, RECEIVER_NOT_EXPORTED)
        } else {
            applicationContext.registerReceiver(object : BroadcastReceiver(){
                override fun onReceive(context: Context?, intent: Intent?) {
                    val message: String? = intent?.extras?.getString("")
                    Log.i("TEST", "收到消息： $message")
                }
            }, filter)
        }


        setContent {
            AppTheme {
                MainView(freshButtonClick = {
                    if (mBound) {
                        mqttService.publish("home/bedroom/ir", "Android TEST")
                    }
                })
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainView(
    freshButtonClick: () -> Unit
) {
    val navController = rememberNavController()
    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text(text = "Smart Home") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.primary,
                ),
                actions = {
                    TextButton(onClick = freshButtonClick
//                    {
//                        navController.currentDestination?.let {
//                            navController.navigate(
//                                it.id
//                            )
//                        }
//                    }
                    ) {
                        Icon(
                            Icons.Default.Refresh,
                            contentDescription = "Refresh"
                        )
                    }
                }
            )
        },
        bottomBar = {},
        floatingActionButton = {
            FloatingActionButton(onClick = { }
            ) {
                Icon(Icons.Default.Add, contentDescription = "Add")
            }
        },
    ) { innerPadding ->
        NavHost(
            navController = navController,
            startDestination = ROUTE_SWITCH,
            modifier = Modifier.padding(innerPadding)
        ) {
            composable(route = ROUTE_HOME) {
                HomeView(navController)
            }
            composable(route = ROUTE_IR_REMOTE_CONTROLLER) {
                InfraredRemoteController()
            }
            composable(route = ROUTE_SWITCH) {
                SwitchView()
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun MainViewPreview() {
    AppTheme {
        MainView {
            Log.d("MainViewPreview", "Fresh Button Clicked")
        }
    }
}

